package org.jeecg.modules.yw.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.modules.yw.entity.Appointment;
import org.jeecg.modules.yw.entity.EnterPrise;
import org.jeecg.modules.yw.entity.FileInfo;
import org.jeecg.modules.yw.entity.FlPrice;
import org.jeecg.modules.yw.entity.MeasureAppoint;
import org.jeecg.modules.yw.entity.Messages;
import org.jeecg.modules.yw.entity.Order;
import org.jeecg.modules.yw.entity.PaperInfo;
import org.jeecg.modules.yw.entity.PriceRules;
import org.jeecg.modules.yw.entity.PriceRulesEnterprise;
import org.jeecg.modules.yw.entity.Rulerpaper;
import org.jeecg.modules.yw.result.Result;
import org.jeecg.modules.yw.service.AppointmentService;
import org.jeecg.modules.yw.service.DataStatisticService;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.service.FileInfoService;
import org.jeecg.modules.yw.service.FlPriceService;
import org.jeecg.modules.yw.service.IRulerpaperService;
import org.jeecg.modules.yw.service.IWorkerCompanyRelationService;
import org.jeecg.modules.yw.service.MeasureAppointService;
import org.jeecg.modules.yw.service.MessagesService;
import org.jeecg.modules.yw.service.OrderQueryService;
import org.jeecg.modules.yw.service.OrderService;
import org.jeecg.modules.yw.service.PageInfoService;
import org.jeecg.modules.yw.service.PriceRulesService;
import org.jeecg.modules.yw.service.SysAnnoucementService;
import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecg.modules.yw.utils.DESUtil;
import org.jeecg.modules.yw.utils.DateUtils;
import org.jeecg.modules.yw.vo.EnterPriseVo;
import org.jeecg.modules.yw.vo.MeasureAppointVo;
import org.jeecg.modules.yw.vo.MessageVo;
import org.jeecg.modules.yw.vo.OrderAccptOrNotVo;
import org.jeecg.modules.yw.vo.OrderQueryVO;
import org.jeecg.modules.yw.vo.OrderVo;
import org.jeecg.modules.yw.vo.OrderappointVo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/app/order")
@Api(tags = "订单管理")
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private PageInfoService pagerService;

    @Resource
    private EnterPriseService enterpriseService;

    @Resource
    private SysAnnoucementService sysAnnoucementService;

    @Resource
    private MeasureAppointService measureAppointService;

    @Resource
    private FileInfoService fileInfoService;
    @Resource
    private MessagesService messageService;
    @Resource
    private OrderQueryService orderQueryService;
    @Resource
    private IRulerpaperService rulerpaperService;
    @Resource
    private DataStatisticService dataStatisticService;
    
    @Resource
    private PriceRulesService priceRuleService;
    
    @Resource
    private FlPriceService flPriceService;
    
    @Resource
    private IWorkerCompanyRelationService workRelationService;
    @Resource
    private AppointmentService appointmentService;
    
    /*
     * 添加企业信息
     * */
    @ApiOperation(value = "添加订单信息  (1. ownerPhone:联系人电话  2. ownerName:业务主方联系人 3. ownerAddress:业务主方联系电话  4. fl:是否需要含辅料 (1: 是 0：否)) 5. cc:是否需要现场改变洞口尺寸(1: 是 0：否) 6. ccfs:旧拆窗拆除方式(1:需要 0:否) "
            + "7. cclx:具体拆除方式( 0: 无  1: 朔窗 2. 铝合金 3 工费拆除是 4 工程拆除否) 8. cpby: 产品搬运(1：电梯 2. 楼梯 3. 提升机 4 超大窗吊车卸车) 9.sghj: 施工环境（1：毛坯 0：已装修）10.sfjj:  0：无 1. 内玻璃胶 2. 外玻璃胶 3. 内墙体胶  11.yyTime:预约时间 12. 上传图纸数组:  pageInfoList (1. type: 安装品类图纸及面积(1:铝包木2. 实木门窗 3. 系统门窗 4. 断桥铝门窗 5. 阳光房 6 采光井 7. 大窗 8. 超大窗 ) 2. paper:图片路径 3. area: 图纸面积 ) )")
    @PostMapping("/addOrder")
    @ResponseBody
    public synchronized Result<String> addOrder(HttpServletRequest request, @RequestBody Order order) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
		// 检查用户是否登录
		if (id == null) {
			return Result.error("您还未登录，无法下单");
		}    	
        order.setCreateUserId(id);
        // 直接将如上内容解密  	
        orderService.addOrder(order);
        // 保存图纸信息 将订单id 与图纸绑定
        List<PaperInfo> pageInfoList = order.getPageInfoList();	        
        FlPrice priceObj = flPriceService.getAllInfoByEnterpriseId(id);
        if (priceObj == null) {
        	priceObj = flPriceService.getFlPriceById(1);
        }	        
        Map<Integer, List<PriceRulesEnterprise>> ruleList = priceRuleService.getAllRuluesByEnterpriseId(id);
        int flag = 1;
        Map<Integer, List<PriceRules>> list = priceRuleService.getAllRulues();
        if (ruleList == null || ruleList.size() == 0) {
        	flag = 0;
        }
        for (PaperInfo obj : pageInfoList) {
            obj.setOrderId(order.getId());
            obj.setCreateTime(DateUtils.getCurrentTimeDateStr());
            if (flag == 0) {
            	String price = priceRuleService.getPriceByRule(Integer.parseInt(obj.getType()), obj.getArea(), order.getFl(), order.getSfjj(), order.getJjlx(), list, priceObj);
            	obj.setPaperPrice(price);
            } else {
            	String price = priceRuleService.getPriceByRuleEnterprise(Integer.parseInt(obj.getType()), obj.getArea(), order.getFl(), order.getSfjj(), order.getJjlx(), ruleList, priceObj);
            	obj.setPaperPrice(price);
            }           
            pagerService.save(obj);
        }
        return Result.success("添加成功");
    }


    @ApiOperation(value = "获取是否有新消息 返回(data 1: 有消息 0:无消息)")
    @GetMapping("/getMsg")
    public Result getMsg(HttpServletRequest request) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        // 检查用户是否登录
        if (id == null) {
            return Result.error("未登录,无消息");
        }
        int isMsg = messageService.IfHasMessages(id);
        return Result.success(isMsg);
    }
    @ApiOperation(value = "工人、组长、打胶点击已知悉")
    @PostMapping("/confirmMessage")
    public Result confirmMessage(HttpServletRequest request, @RequestBody OrderAccptOrNotVo vo) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        EnterPrise ent = enterpriseService.getById(id);
        if (ent ==null ){
            return Result.error("用户不存在");
        }
        String reason = Optional.ofNullable(vo.getReaason()).orElse("");
        //更新消息 为已读状态
        messageService.updateMessage(vo.getId(), vo.getReaason() == null ? "" : reason,vo.getRemark() ==null? "" : vo.getRemark());
        return Result.success("true");
    }
    @ApiOperation(value = "安装班组(组长,组员)、打胶售后接受/拒绝1. (1. accpt: 1:接受 2：拒绝)、 2. orderId: 订单id, 3 reason: 拒绝原因  4. 消息id: id")
    @PostMapping("/acceptOrNot")
    public Result acceptOrNot(HttpServletRequest request, @RequestBody OrderAccptOrNotVo vo) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        EnterPrise ent = enterpriseService.getById(id);
        Messages message = messageService.getById(vo.getId());
        Integer isLeader = ent.getIsleader();
        Integer roleId = ent.getRoleid();
        if (isLeader != null && isLeader == 2) {
            //安装班组组员接单
            if (vo.getOrderId()==null  || vo.getOrderId().equals("")){
                String reason = vo.getReaason();
                messageService.updateMessage(vo.getId(), vo.getReaason() == null ? "" : reason,vo.getRemark() ==null? "" : vo.getRemark());
                return Result.success("true");
            }
            Order order = orderService.getOrder(message.getOrderId());
            String yyTime = order.getYyTime().substring(0, 10);
            Appointment appointment = new Appointment();
            appointment.setAppointTime(yyTime);
            appointment.setAppointId(id);
            appointment.setName(ent.getName());
            appointment.setOrderId(message.getOrderId());
            List<Appointment> list = orderService.selectAppointAccpt(appointment);
            if (vo.getAccpt() == 2 && list != null && list.size() > 0) {
                //return Result.error("预约人已接受,不可拒绝");
            }
            appointment.setAppointType(String.valueOf(vo.getAccpt()));
            orderService.accpAppointment(appointment);
            String workerIds = workRelationService.getWorkersByCompanyId(order.getCreateUserId());
            Messages m =new Messages();

            if (vo.getAccpt() == 1) {
//            	sysAnnoucementService.AddSysAnnoucement("安装班组接单消息", "订单编号: "+order.getOrderNo()+"业主联系地址"+order.getOwnerAddress()+"组员接单", "5", id, workerIds, vo.getOrderId(),"0");
            	dataStatisticService.insertTjsl(id, 2, message.getOrderId(), 1, "1");
                m.setRemark("安装组组员:"+ appointment.getName()+" 已接受" +"\n"+"预约时间:"+appointment.getAppointTime());
                Order o = new Order();
                o.setId(message.getOrderId());
                o.setTeamRead(1);
                o.setUserId(id);
                orderService.updateOrderInfo(o);
            } else {
//            	sysAnnoucementService.AddSysAnnoucement("安装班组消息", "组员拒绝接单", "7", id, workerIds, vo.getOrderId(),"0");
                m.setRemark("安装组组员:"+appointment.getName()+" 已拒绝" +"\n"+"订单编号:"+order.getOrderNo());
            }
            m.setId(CommonUtils.getID());
            m.setOrderId(message.getOrderId());
            m.setDelFlag(0);
            m.setOrderNo(order.getOrderNo());
            m.setMsgType(2);
            m.setState(0);
            m.setCurrentUserId(order.getAzbzUserId());
            messageService.save(m);
        } else {
            //组长接受或拒绝
            if (vo.getAccpt() == 1) {
                // 接受
                Order order = new Order();
//                if (vo.getOrderId() == null){
//                    String reason = vo.getReaason();
//                    messageService.updateMessage(vo.getId(), vo.getReaason() == null ? "" : reason,vo.getRemark() ==null? "" : vo.getRemark());
//                    return Result.success("true");
//                }
                order.setId(message.getOrderId());
                order.setUserId(id);
                Order orderInfo = orderService.getOrder(message.getOrderId());
                String workerIds = workRelationService.getWorkersByCompanyId(orderInfo.getCreateUserId());
//                sysAnnoucementService.AddSysAnnoucement("安装班组接单消息", "组长接单", "5", id, "0", vo.getId(), "0");
                if (roleId == 1) {
                    if (order.getMcschsState()!=null&& order.getMcschsState() == 1) {
                        order.setMcschsState(2);
                    }
                    if (order.getMcdkfcState()!=null&& order.getMcdkfcState() == 1 ) {
                        order.setMcdkfcState(2);
                    }
                    if (message.getOrderMsgType()!=null && 7 == message.getOrderMsgType() && orderInfo.getOrderStatus() == 9) {
                    	order.setOrderStatus(10);
                    	order.setJstime(DateUtils.strToDateTime(DateUtils.getCurrentTimeDateStr()));
                        sysAnnoucementService.AddSysAnnoucement("门窗企业结算确认消息", "订单编号: "+orderInfo.getOrderNo()+
                                ";业主联系地址:"+orderInfo.getOwnerAddress()+ ";门窗企业:"+ent.getName(), "14", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(), ent.getCityCode());
                    }
                }
                if (roleId == 2) {
                	// 安装班组待处理订单
                	if (message!=null && message.getOrderMsgType()!=null && 1 == message.getOrderMsgType()  ) {
                	   order.setYpzzbz("安装班组人员:"+ent.getName() + "(已接受)");
                	   order.setAzbzUserId(id);
                	   order.setOrderStatus(1);//证明组长接受订单
                	   order.setState(3);//中控不可退订单
                       sysAnnoucementService.AddSysAnnoucement("安装班组接单消息", "订单编号: "+orderInfo.getOrderNo()+
                               "业主联系地址:"+orderInfo.getOwnerAddress()+ "安装班组接单人:"+ent.getName(), "5", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(),ent.getCityCode());
                       dataStatisticService.insertTjsl(id, 1, message.getOrderId(), 1, "1");
                    }
                }
                if (roleId == 3) {
                	// 打胶售后待处理订单
                	if (message !=null && message.getOrderMsgType()!=null && 4 == message.getOrderMsgType()) {
                		order.setYpdjsh("打胶售后人员:"+ent.getName() + "(已接受)");
                		order.setDjshUserId(id);
                		String oId = message.getOrderId();
                		Order o = orderService.getById(oId);
                			if (o.getOrderStatus() == 5) {
                				order.setOrderStatus(6);
                			}
//                		if (StringUtils.isBlank(orderInfo.getDjTime())) {
//                			order.setDjTime(orderInfo.getYyTime());
//                		}
                        sysAnnoucementService.AddSysAnnoucement("打胶售后接单消息", "订单编号:"+o.getOrderNo()+
                                "业主联系地址"+orderInfo.getOwnerAddress()+"打胶售后接单人"+ent.getName(), "10", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(), ent.getCityCode());
                        dataStatisticService.insertTjsl(id, 3, message.getOrderId(), 1, "1");
                    }
                }
                orderService.updateOrderInfo(order);
            } else {
                // 安装班组/打胶售后拒绝接单
                Order order = new Order();
                order.setId(message.getOrderId());
                order.setCurrentUserId("0");
                order.setUserId(id);
                String r = vo.getReaason();
                Order orderInfo = orderService.getOrder(message.getOrderId());
                String workerIds = workRelationService.getWorkersByCompanyId(orderInfo.getCreateUserId());
                if ("1"== r){
                    vo.setRemark("已有订单未完成");
                }else if ("2"== r){
                    vo.setRemark("今日订单已满");
                }
                if (roleId == 1) {
                	  if (message.getOrderMsgType()!=null && 7 == message.getOrderMsgType()) {
	                      	order.setOrderStatus(8);
	                      	order.setJsPath("  ");
	                      	order.setJsReason(vo.getRemark());
                            sysAnnoucementService.AddSysAnnoucement("门窗企业结算驳回消息", "订单编号: "+orderInfo.getOrderNo()+
	                                 "业主联系地址:"+orderInfo.getOwnerAddress()+ "门窗企业:"+ent.getName()+",驳回原因:"+vo.getRemark(), "14", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(), ent.getCityCode());
                      }
                }
                if (roleId == 2) {
                	if (message !=null&&message.getOrderMsgType()!=null&& 1 == message.getOrderMsgType()) {
                		order.setYpzzbz("安装班组人员:"+ent.getName() + "(已拒绝)");
                    	order.setStatus(2); //
                    	order.setAzbzUserId("0");
                    	order.setAzbzReason(vo.getReaason());
                    	order.setState(1);
                        sysAnnoucementService.AddSysAnnoucement("安装班组拒绝接单消息", "订单编号: "+orderInfo.getOrderNo()+
                                "安装班组拒绝接单人:"+ent.getName()+"拒绝原因:"+vo.getRemark(), "6", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(), ent.getCityCode());
                    }
                }
                if (roleId == 3) {
                     if (message !=null &&message.getOrderMsgType()!=null&& 4 == message.getOrderMsgType()) {
                    	order.setYpdjsh("打胶售后人员:"+ent.getName() + "(已拒绝)");
	                    order.setStatus(5); // 打胶售后拒绝消息
	                    order.setDjshUserId("0");
	                    order.setDjshReason(vo.getReaason());
	                    order.setState(1);
                        sysAnnoucementService.AddSysAnnoucement("打胶售后拒绝接单消息", "订单编号: "+orderInfo.getOrderNo()+
                                "打胶售后拒绝接单人:"+ent.getName()+"拒绝原因:"+vo.getRemark(), "11", id, workerIds, message.getOrderId(),"0", orderInfo.getOrderNo(), ent.getCityCode());
                	}
                }
                orderService.updateOrderInfo(order);
            }
        }
        String reason = vo.getReaason();
        messageService.updateMessage(vo.getId(), vo.getReaason() == null ? "" : reason,vo.getRemark() ==null? "" : vo.getRemark());
//        sysAnnoucementService.AddSysAnnoucement("安装组员拒绝接单", "组员拒绝接单", "7", id, "0", vo.getId());
        return Result.success("true");
    }


    /*
     * 修改订单信息
     * */
    @ApiOperation(value = "修改订单信息")
    @PostMapping("/updateOrder")
    @ResponseBody
    public Result<String> updateOrder(HttpServletRequest request,@RequestBody OrderVo order) {
        String token = request.getHeader("token");
        String userId = DESUtil.decryptCBCId(token);
        Order o = orderService.getById(order.getId());
        //Integer AzsgStatus = o.getAzsgStatus();
        if (order.getAzsgStatus() != null && order.getAzsgStatus() == 2){
            Date now = DateUtils.getCurrentDate();
            String yyTime = o.getYyTime();
            //比较时间
            if (yyTime != null && !yyTime.isEmpty()) {
                Date yyTimeDate = DateUtils.strToDateTime(yyTime);
                // 将 Date 转换为 LocalDate
                LocalDate nowLocalDate = now.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                LocalDate yyTimeLocalDate = yyTimeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                if (yyTimeLocalDate.isAfter(nowLocalDate)) {
                    return Result.error("未到预约日期，无法签到");
                }
            }
        }
        order.setUserId(userId);
        orderService.updateOrderInfo(order);
        if (order.getFileInfoList() != null){
        for (FileInfo file : order.getFileInfoList()) {
	        if (file.getBusiType() != null) {
	            String id = CommonUtils.getID();
	            file.setId(id);
	            file.setFileId(order.getId());
	            fileInfoService.save(file);
	        }
        }
        }
        return Result.success();
    }


    /*
     * 添加预约人信息
     * */
    @ApiOperation(value = "添加预约人信息")
    @PostMapping("/addAppointment")
    @ResponseBody
    public Result<String> addAppointment(HttpServletRequest request, @RequestBody Appointment appointment) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        //前端会传来每次最新的预约人信息
        String orderId= "";
        String appointTime = "";
        List<Appointment> list = new ArrayList<>();
        
        
        for (Appointment obj : appointment.getAppointmentList()) {
            obj.setBzzId(id);
            if (StringUtils.isNotBlank(obj.getAppointId()) && !obj.getAppointId().equals(id)) {
            	list.add(obj);
            }            
//            orderId = obj.getOrderId();
//            Order order  = orderService.getById(orderId);
//            appointTime = order.getYyTime();
//            Date appointDate = DateUtils.strToDateTime(appointTime);
//            UpdateWrapper<Appointment>  upWrapper = new UpdateWrapper<>();
//            upWrapper.eq("orderId", orderId);
//            upWrapper.eq("appointTime", appointDate);
//            upWrapper.set("delFlag",1);
//            boolean r = appointmentService.saveOrUpdate(obj, upWrapper);
            //删除原有预约人信息  再根据orderid查消息列表查出 没有点击确认或者点击拒绝的预约人
//            QueryWrapper<Messages> mWrapper = new QueryWrapper<>();
//            mWrapper.eq("orderId", orderId);
//            List<Messages> messages = messageService.list(mWrapper);
//            if (messages != null) {
//                for (Messages m : messages) {
//                    UpdateWrapper<Messages> messagesQueryWrapper = new UpdateWrapper<>();
//                    messagesQueryWrapper.eq("orderId", orderId);
//                    messagesQueryWrapper.eq("yyTime", appointDate);
//                    messagesQueryWrapper.eq("state", 0);
//                    messagesQueryWrapper.set("delFlag", 0);
//                    messageService.saveOrUpdate(m, messagesQueryWrapper); //删除未处理的消息列表
//                }
//            }
        }
        orderService.addAppointment(list);
        return Result.success();
//        Appointment obj = appointment.getAppointmentList().get(0);
//    	 String yyTime = order.getYyTime().substring(0, 10);
//    	 obj.setAppointTime(yyTime);
//    	 List<Appointment> list =  orderService.selectAppointAccpt(obj);    	 
//    	 for (Appointment app : list) {
// 	    	String uid = CommonUtils.getID();
// 	    	app.setId(uid);
// 	    	app.setAppointType("0");
// 	    	app.setCreateTime(DateUtils.getCurrentTimeDateStr());    
// 	    	app.setBzzId(id);
//    		orderService.addAppointment(app);
//    	 }    
//        Order order1 = new Order();
//        order1.setId(obj.getOrderId());
//        order1.setOrderStatus(2);
//        orderService.updateStatus(order1);
    }
    @ApiOperation(value = "修改订单状态")
    @PostMapping("/confirmStatus")
    public Result<String> updateStatus(@RequestBody Order order) {
        order.setAzsgStatus(1);
        orderService.getBaseMapper().updateOrderInfo(order);
//        QueryWrapper<Messages> messagesQueryWrapper = new QueryWrapper<>();
//        messagesQueryWrapper.eq("orderId", order.getId());
//        messagesQueryWrapper.eq("state", 0);
//        messageService.remove(messagesQueryWrapper);
        return Result.success();
    }

    @ApiOperation(value = "中控---查看订单")
    @GetMapping("/getOrderInfo")
	public org.jeecg.common.api.vo.Result getOrderInfo(@RequestParam(name = "id") String id){
        Order order = orderService.getOrder(id);
        QueryWrapper<PaperInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("orderId", id);
        order.setPageInfoList(pagerService.list());
        return org.jeecg.common.api.vo.Result.ok(order);
    }
    @ApiOperation(value = "中控---接单")
    @GetMapping("/acceptOrder")
    public org.jeecg.common.api.vo.Result acceptOrder(@RequestParam String id) {
        Order info = orderService.getById(id);
        // 中控接单
        info.setState(1);
        orderService.updateById(info);
        return org.jeecg.common.api.vo.Result.ok();
    }

    @ApiOperation(value = "中控---退单")
    @GetMapping("/backOrder")
    public org.jeecg.common.api.vo.Result backOrder(@RequestParam String id) {
        Order info = orderService.getById(id);
        info.setDelFlag(1);
        orderService.updateById(info);
        
        return org.jeecg.common.api.vo.Result.ok();
    }
    @ApiOperation(value = "中控---派单（代做）")
    @PostMapping("/assignOrder")
    public org.jeecg.common.api.vo.Result assignOrder(@RequestBody OrderVo order) {
        Order info = orderService.getById(order.getId());
//        // TODO
//        orderService.updateById(info);
    	if (StringUtils.isNotBlank(order.getAzbzUserId())) {
	        QueryWrapper<Messages> queryWrapper  = new QueryWrapper<>();
	        queryWrapper.eq("msgType", 1);
	        queryWrapper.eq("orderMsgType", 1);
	        queryWrapper.eq("state", 0);     
	        queryWrapper.eq("delFlag", 0);   
	        queryWrapper.eq("currentUserId", order.getAzbzUserId());
	        queryWrapper.eq("orderId", order.getId());
	        List<Messages> list = messageService.list(queryWrapper);
	        if (list != null && list.size() > 0){
	        	return org.jeecg.common.api.vo.Result.error("该班组长已派单，请勿重复派单");
	        }  	        
    	}
        if (StringUtils.isNotBlank(order.getDjshUserId())) {
	        QueryWrapper<Messages> queryWrapper1  = new QueryWrapper<>();
	        queryWrapper1.eq("msgType", 1);
	        queryWrapper1.eq("orderMsgType", 4);
	        queryWrapper1.eq("state", 0);     
	        queryWrapper1.eq("delFlag", 0);   
	        queryWrapper1.eq("currentUserId", order.getDjshUserId());
	        queryWrapper1.eq("orderId", order.getId());
	        List<Messages> list1 = messageService.list(queryWrapper1);
	        if (list1 != null && list1.size() > 0){
	        	return org.jeecg.common.api.vo.Result.error("该打胶售后人员已派单，请勿重复派单");
	        }  
        }
        if (StringUtils.isNotBlank(order.getAzbzUserId())) {
	        if (StringUtils.isNotBlank(info.getYpzzbz()) && !"0".equals(info.getAzbzUserId())) {
	        	return org.jeecg.common.api.vo.Result.error("该订单安装组长已派单，请查看派单详情");
	        }
        }
        if (StringUtils.isNotBlank(order.getDjshUserId())) {
        	 if (StringUtils.isNotBlank(info.getYpdjsh()) && !"0".equals(info.getDjshUserId())) {
 	        	return org.jeecg.common.api.vo.Result.error("该订单打胶售后已派单，请查看派单详情");
 	        }
        }        
        
        int zkpd = orderService.zkpd(order.getId(), order.getAzbzUserId(), order.getDjshUserId());
        if (zkpd!=1){
            return org.jeecg.common.api.vo.Result.error("派单失败");
        }
//    	if (StringUtils.isNotBlank(order.getMsgId())) {
//    		sysAnnoucementService.updateMsg(order.getMsgId());
//    	}
        return org.jeecg.common.api.vo.Result.ok();
    }
    
    @ApiOperation(value = "中控---提交结算")
    @PostMapping("/jsOrder")
    public org.jeecg.common.api.vo.Result jsOrder(@RequestBody OrderVo order) {
        orderService.zkjs(order.getId(), order.getJsPath());
        return org.jeecg.common.api.vo.Result.ok();
    }



    @ApiOperation(value = "中控---输入金额")
    @PostMapping("/jsPrice")
    public org.jeecg.common.api.vo.Result confirmOrderPrice(@RequestBody OrderVo order) {
        orderService.confirmOrder(order.getId(), order.getFinalPrice());
        return org.jeecg.common.api.vo.Result.ok();
    }


    @ApiOperation(value = "中控---已付款")
    @PostMapping("/confirmPay")
    public org.jeecg.common.api.vo.Result confirmPay(@RequestBody OrderVo order) {
        orderService.confirmPay(order.getId());
        return org.jeecg.common.api.vo.Result.ok();
    }


    @ApiOperation(value = "中控---预约量尺功能")
    @PostMapping("/appointInfo")
    public org.jeecg.common.api.vo.Result appointInfo(@RequestBody OrderappointVo vo) {
        UpdateWrapper<MeasureAppoint> wrapper = new UpdateWrapper<>();
        wrapper.lambda().eq(MeasureAppoint::getId,vo.getId())
                .set(MeasureAppoint::getMj,vo.getMj())
                .set(MeasureAppoint::getJe,vo.getJe());
        measureAppointService.update(wrapper);
        if (vo.getPics() != null) {
            UpdateWrapper<Rulerpaper> wrapper1 = new UpdateWrapper<>();
            wrapper1.lambda().eq(Rulerpaper::getOrderid,vo.getId());
            rulerpaperService.remove(wrapper1);
            for (int i=0;i<vo.getPics().size();i++) {
                String pic = vo.getPics().get(i);
                Rulerpaper rulerpaper = new Rulerpaper();
                rulerpaper.setOrderid(vo.getId());
                rulerpaper.setPageurl(pic);
                rulerpaper.setSorted(i);
                rulerpaperService.save(rulerpaper);
            }
            QueryWrapper<MeasureAppoint> q = new QueryWrapper<>();
            q.eq("id",vo.getId());
            MeasureAppoint measureAppoint = measureAppointService.getOne(q);
            Messages messages =new Messages();
            messages.setId(CommonUtils.getID());
            messages.setState(0);
            messages.setMsgType(2);
            messages.setOwnerAddress(measureAppoint.getContactAddress());
            messages.setRemark("预约量尺完成");
            messages.setDelFlag(0);
            messages.setMsgTime(DateUtils.getCurrentTimeDateStr());
            messages.setCurrentUserId(measureAppoint.getCreator());
        }
        return org.jeecg.common.api.vo.Result.ok();
    }
    //获取预约量尺列表
    @ApiOperation(value = "本人获取预约量尺列表")
    @GetMapping("/getMeasureAppointList")
    public Result getMeasureAppointList( HttpServletRequest request,
                                        @RequestParam(name = "pageNo") Integer pageNo,
                                        @RequestParam(name = "pageSize") Integer pageSize) {
        String t = request.getHeader("token");
        String id = DESUtil.decryptCBCId(t);
        IPage<MeasureAppoint> iPage = measureAppointService.getpageList(pageNo, pageSize, id);
        List<MeasureAppoint> records = iPage.getRecords();

        for (MeasureAppoint measureAppoint : records){
            List<Rulerpaper> rulerpaperList = rulerpaperService.list(new QueryWrapper<Rulerpaper>().lambda()
                    .select(Rulerpaper::getPageurl, Rulerpaper::getOrderid)
                    .eq(Rulerpaper::getOrderid, measureAppoint.getId()));
            measureAppoint.setRulerpaperList(rulerpaperList);
        }
        long total = iPage.getTotal();
        long size = iPage.getSize();
        long current = iPage.getCurrent();
        HashMap<String, Object> map = new HashMap<>();
        map.put("records", records);
        map.put("total", total);
        map.put("size", size);
        map.put("current", current);
        if (iPage == null){
            return Result.error("操作失败");
        }
        return Result.success(map);
    }
    
    @ApiOperation(value = "获取可预约人员列表")
    @GetMapping("/getAllAvailable")
    public Result getAll(HttpServletRequest request, @RequestParam(value = "orderId")  String orderId) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        EnterPrise ent = enterpriseService.getById(id);
        Order order = orderService.getById(orderId);
        String yyTime = order.getYyTime();
        String bzzId = order.getAzbzUserId();
        // 查询当天之前预约已接收人员 第一单的
        List<EnterPriseVo> list = orderService.selectAppointsByAppointTimeAndOrderId(bzzId, yyTime.substring(0,10), orderId);
        // 工单池里的人
        List<EnterPriseVo> result = orderService.selectAppointAvailable(yyTime.substring(0,10),bzzId, ent.getCityCode());
        if (list!=null && list.size()>0){
            order.setAzsgStatus(1);
            orderService.updateById(order);            
            List<EnterPriseVo> newList =  new ArrayList<>();            
            Map map = new HashMap();            
            for (EnterPriseVo vo : list) {            	
            	if (!map.containsKey(vo.getId())) {
            		newList.add(vo);
            	}
            	map.put(vo.getId(), vo.getId());
            }                        
	    	
            // 添加人员
//            for (EnterPriseVo obj: newList) {
//            	Appointment  app = new Appointment();
//            	String aid = CommonUtils.getID();
//            	app.setId(aid);
//            	app.setAppointType("1");
//            	app.setOrderId(orderId);
//            	app.setAppointId(obj.getId());
//            	app.setAppointTime(obj.getAppointTime());
//            	app.setCreateTime(DateUtils.getCurrentTimeDateStr()); 
//            	app.setBzzId(obj.getBzzId());
//            	app.setName(obj.getName());
//    	    	appointmentService.getBaseMapper().insertAppointment(app);
//            }
            
            return Result.success(newList);
        }
        return Result.success(result);
    }

    
//    @ApiOperation(value = "获取可预约人员列表")
//    @GetMapping("/getAllAvailable")
//    public Result getAll(@RequestParam(value = "orderId")  String orderId) {
//    	Result result = new Result();
//        Order order = orderService.getById(orderId);
//        String yyTime = order.getYyTime();
//        List<Appointment> list = orderService.selectAppointsByAppointTimeAndOrderId(yyTime);
//        if (list != null && list.size() > 0) {
//        	result.setCode(2);
//        	result.setData(list);
//        } else {        
//        	List<EnterPriseVo> rList = orderService.selectAppointAvailable(yyTime);
//        	result.setData(rList);
//        }        
//        return result;
//    }

    /*
     * 更新订单状态和相关环节状态
     * */
    @ApiOperation(value = "更新订单状态和相关环节状态  oorderStatus(0: 待接订单 1：已接订单 3 施工中订单4. 安装班组完成  5. 打胶售后待接订单  6 打胶售后施工中订单 7. 打胶售后施工完成订单  8. 结算待确认订单 9 已结算完成), "
            + "azsgStatus(安装班组施工状态 1 确定人员 2. 人员签到 3. 查损核数 4. 洞口复测 5. 固定方式 6. 玻璃执手 7. 人走场清 8. 告知售后), djshStatus(打胶施工状态 1.到达预约地点 2. 开始质检 3. 打胶施工 4. 指导业主正确打开门窗 5. 上传验收单) ")
    @PostMapping("/updateOrderStatus")
    @ResponseBody
    public Result<String> addAppointment(@RequestBody Order order) {
        orderService.updateStatus(order);
        return Result.success();
    }


    @ApiOperation(value = "获取订单详细信息")
    @GetMapping("/getOrderInfoById")
    public Result getOrderInfoById(@RequestParam(value = "id") String id) {
        return Result.success(orderService.getOrder(id));
    }

    /*
     * 预约量尺功能
     * */
    @ApiOperation(value = "预约量尺功能请求参数： 1、appointment_time:预约时间 2、contact_address:业主方联系地址 3、contact_phone:业主方联系电话 4、measurement_area:大概面积 5、contact_name:业主方联系姓名")
    @PostMapping("/addMeasureAppoint")
    public Result addAppointment(@RequestBody MeasureAppointVo measureAppointVo, HttpServletRequest request) throws Exception {
        String token = request.getHeader("token");
        System.out.println("接到的" + token);
        String id = DESUtil.decryptCBCId(token);
        // 检查用户是否登录
        if (id == null) {
            return Result.error("您还未登录，无法预约量尺");
        }
        EnterPrise enterPrise = enterpriseService.getById(id);
        Integer roleid = enterPrise.getRoleid();
        if (roleid != 1) {
            return Result.error("您不是门窗安装组人员，无法预约量尺");
        }
        // 调用服务层方法处理预约
        return measureAppointService.addAppointment(measureAppointVo, id);
    }

    @ApiOperation(value = "订单评价")
    @PostMapping("/orderEvaluate")
    public Result orderEvaluate(@RequestBody OrderVo orderVo, HttpServletRequest request) {
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        EnterPrise enterPrise = enterpriseService.getById(id);
        Integer roleid = enterPrise.getRoleid();
        if (roleid != 1) {
            return Result.error("您不是门窗企业人员，无法评价");
        }
        String orderNo = orderVo.getOrderNo();
        if (StringUtils.isBlank(orderNo)) {
            return Result.error("订单编号不能为空");
        }
        Order order = orderService.getOrderByOrderNo(orderNo);
        Integer orderStatus = order.getOrderStatus();
        if (11 != orderStatus) {
            return Result.error("订单未到评价阶段，无法评价");
        }

        UpdateWrapper<Order> updateWrapper = new UpdateWrapper<>();
        UpdateWrapper<Order> orderUpdateWrapper = updateWrapper
                .eq("orderNo", orderNo)
                .set("orderStatus", 12)
                .set("evaluate_content", orderVo.getEvaluateContent())
                .set("order_service", orderVo.getOrderService())
                .set("install_service", orderVo.getInstallService())
                .set("caulking_service", orderVo.getCaulkingService());
        orderService.update(orderUpdateWrapper);
        return Result.success("评价完成");
    }


    @ApiOperation(value = "订单列表")
    @GetMapping("/pageOrders")
    public Result pageEnter(HttpServletRequest request, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,  @RequestParam(name = "orderStatus", defaultValue = "") String orderStatus
                            , @RequestParam(name = "orderNo", defaultValue = "") String orderNo) {
        QueryWrapper<OrderQueryVO> queryWrapper = new QueryWrapper<>();

        Integer offset = (pageNo - 1) * pageSize;

        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
        EnterPrise ent = enterpriseService.getById(id);
        Page<OrderQueryVO> page = new Page<>(pageNo, pageSize);
        List<OrderQueryVO> result = orderQueryService.getOders(page, queryWrapper, id, ent.getRoleid(), ent.getIsleader(), offset, pageSize, orderStatus, orderNo);
        return Result.success(result);
    }


    @ApiOperation(value = "最新实时消息")
    @GetMapping("/pageMsgOrders")
    public Result pageMsgEnter(HttpServletRequest request, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        String token = request.getHeader("token");
        String id = DESUtil.decryptCBCId(token);
       // id = "6e4757f838314cca9895a2af18874cf9";
        List<MessageVo> obj = messageService.getLatestMessage(id, pageNo, pageSize);
        if (obj == null) {
            return Result.error("暂无消息");
        }

        return Result.success(obj);
    }
    @ApiOperation(value = "今日订单数量")
    @GetMapping("/todayOrders")
    public Result todayOrders(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error("未登录");
        }
        String id = DESUtil.decryptCBCId(token);
        EnterPrise enterPrise = enterpriseService.getById(id);
        if (enterPrise == null) {
            return Result.error("未找到对应的个人信息");
        }

        List<Map<String, Object>> resultList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (int i = 0; i < 7; i++){
            Date currentDate = calendar.getTime();
            String startTime = DateUtils.getDayStartTimeStr(currentDate);
            String endTime = DateUtils.getDayEndTimeStr(currentDate);
            int count = 0;
            //查询安装/打胶订单数量
            BigDecimal mj = BigDecimal.ZERO;
            // 查询安装/打胶订单
            Map<String, Object> resultMap = new HashMap<>();
            //先判断角色
            if(enterPrise.getRoleid() == 2 && enterPrise.getIsleader()==1){
                //安装班组
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("azbzUserId", id);
                wrapper.ge("yyTime", startTime);
                wrapper.lt("yyTime", endTime);
                List<Order> list = orderService.getBaseMapper().selectList(wrapper);
                if (list != null){
                    count = list.size();
                    for (Order order : list){
                        String areas = order.getAreas();
                        if (areas != null){
                            mj = mj.add(new BigDecimal(areas));
                        }
//                        List<PaperInfo> paperInfoList = pagerService.list(new QueryWrapper<PaperInfo>().eq("orderId", order.getId()));
//                        for (PaperInfo paperInfo : paperInfoList){
//                            mj = mj.add(new BigDecimal(paperInfo.getArea()));
//                        }
                    } //预约时间当天面积
                }
            }
            if(enterPrise.getRoleid() == 3) {
                //打胶售后
                QueryWrapper<Order> wrapper = new QueryWrapper<>();
                wrapper.eq("djshUserId", id)
                        .apply("GREATEST(djTime, yyTime) >= {0} AND GREATEST(djTime, yyTime) < {1}", startTime, endTime);
                List<Order> list = orderService.getBaseMapper().selectList(wrapper);
                if (list != null) {
                    count = list.size();
                    for (Order order : list) {
                        String areas = order.getAreas();
                        if (areas != null){
                            mj = mj.add(new BigDecimal(areas));
                        }
                    }
                }
            }
            if (enterPrise.getRoleid() == 2 &&  enterPrise.getIsleader() == 2){
                QueryWrapper<Appointment> queryWrapper  = new QueryWrapper<>();
                queryWrapper.eq("appointId", enterPrise.getId());
                queryWrapper.ge("appointTime", startTime);
                queryWrapper.lt("appointTime", endTime);
                queryWrapper.eq("appointType", 1);
                List<Appointment> list = appointmentService.list(queryWrapper);
                if (list != null){
                    count = list.size();
                    for (Appointment appointment : list){
                        Order order = orderService.getById(appointment.getOrderId());
                        String areas = order.getAreas();
                        if (areas != null){
                            mj = mj.add(new BigDecimal(areas));
                        }
                    }
                }
            }
            String formattedDate = sdf.format(currentDate);
            resultMap.put("date", formattedDate);
            resultMap.put("count", count);
            resultMap.put("mj", mj);
            if (enterPrise.getRoleid() == 2 ) {
                resultMap.put("azbzUserId", enterPrise.getId());
            } else {
                resultMap.put("djshUserId", enterPrise.getId());
            }
            resultMap.put("azbzUserId", enterPrise.getId());
            resultMap.put("name", enterPrise.getName());
            resultList.add(resultMap);
            // 日期加一天
            calendar.add(Calendar.DAY_OF_YEAR, 1);
        }
        return Result.success(resultList);
    }
    
//
//    @ApiOperation(value = "测试价格")
//    @GetMapping("/testPrice")
//    public Result testPrice(@RequestParam(name = "type", defaultValue = "1") Integer type, @RequestParam(name = "area", defaultValue = "1") String area,
//    		@RequestParam(name = "fl", defaultValue = "1") Integer fl, @RequestParam(name = "sfjj", defaultValue = "1") Integer sfjj, @RequestParam(name = "jjlx", defaultValue = "jjlx") String jjlx) {
////    	  String pice = priceRuleService.getPriceByRule(type, area, fl, sfjj, jjlx);
////    	  return Result.success(pice);
//    }
	  @ApiOperation(value = "测试中控查询")
	  @GetMapping("/testZkQuery")
	  public Result testZkQuery() {
		  //String workerIds = workRelationService.getWorkersByCompanyId("1");
		  
		   	
	    	// 判断当前是几号
	    	String curDate = DateUtils.getDateStr();
	    	String day = curDate.substring(8,10);
	    	String month = curDate.substring(0,7);
	    	String startTime = "";
	    	String endTime = "";
	    	List<Order> list = new ArrayList<Order>();
	    	if (day.equals("10")) {
	    		startTime = month + "-01 00:00:00";
	    		endTime = DateUtils.getCurrentTimeDateStr();
	    		list = orderService.getBaseMapper().selectPaymentOrder(startTime, endTime);
	    		
	    	} else if (day.equals("20")) {
	    		startTime =  month + "-10 09:15:00";
	    		endTime = DateUtils.getCurrentTimeDateStr();
	    		list = orderService.getBaseMapper().selectPaymentOrder(startTime, endTime);
	    		
	    	} else {
	    		startTime =  month + "-20 09:15:00";
	    		endTime = DateUtils.getCurrentTimeDateStr();
	    		list = orderService.getBaseMapper().selectPaymentOrder(startTime, endTime);    		
	    	}
	    	
	    	
	    	for (Order order : list) {
				String createUserId = order.getCreateUserId();
				String price = order.getFinalPrice();
				String jsTime = orderService.getBaseMapper().getJsTime(createUserId, startTime, endTime);			
				Messages message = new Messages();
		    	message.setId(CommonUtils.getID());
		    	message.setMsgType(2);
		    	message.setNormalMsgType(7);
		    	message.setState(0);
		    	message.setMsgTime(DateUtils.getCurrentTimeDateStr());
		    	message.setCurrentUserId(createUserId);
		    	message.setDelFlag(0);	    	
		    	message.setDealTime(jsTime);
		    	message.setRemark(price);
		    	messageService.save(message);			
			}  
		  
		  
		  return Result.success("");
	  }
}

